<template>
  <el-card class="el-card--has-heading success">
    <div slot="header" class="v-card__headerInner">
      <p>维保供应商维保订单</p>
      <transition name="el-zoom-in-center">
        <div v-show="showTip">
          <p class="v-card__header-tip">待上门并且未完成订单可接单</p>
        </div>
      </transition>
    </div>
    <v-table
      :dataSource="dataSource"
      :columns="columns"
      :loading="loading"
      :total="total"
      v-bind="bindProps"
      v-on="bindListeners"
    >
      <template slot="toolbar">
        <el-form inline size="small" :model="query" ref="query" class="flex flex-wrap">
          <el-form-item prop="communityName">
            <el-input placeholder="请输入社区名称" v-model="query.communityName" />
          </el-form-item>
          <el-form-item prop="goodsName">
            <el-input placeholder="请输入商品名称" v-model="query.goodsName" />
          </el-form-item>

          <el-form-item prop="orderState">
            <el-select v-model="query.orderState" placeholder="请选择订单状态">
              <el-option
                v-for="(it, i) in orderStatus.filter(it => it.value !== 1)"
                :key="i"
                :label="it.label"
                :value="it.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="orderReceivingOrders">
            <el-select v-model="query.orderReceivingOrders" placeholder="请选择是否接单">
              <el-option
                v-for="(it, i) in commonLogical"
                :key="i"
                :label="it.label"
                :value="it.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="dateRange">
            <el-date-picker
              size="small"
              v-model="query.dateRange"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="handleSearch">查询</el-button>
            <el-button type="default" @click="onClickBatchExport">导出</el-button>
            <el-button type="warning" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </template>
    </v-table>

    <Modal
      title="接单信息"
      okText="接单"
      :loading="modalLoading"
      :visible.sync="visible"
      :width="$V.size.sm"
      :onOk="handleSubmit"
      :onCancel="handleClose"
    >
      <ConfirmOrderForm :record="record" ref="orderForm" />
    </Modal>

    <Modal
      :title="imageActionType === 'create' ? '完成订单' : '编辑维修图片'"
      :okText="imageActionType === 'create' ? '完成' : '修改'"
      :loading="imageModalLoading"
      :visible.sync="imageModalVisible"
      :width="$V.size.sm"
      :onOk="handleComplete"
      :onCancel="() => imageModalVisible = false"
    >
      <OrderImagesForm :record="imageRecord" ref="imageForm" />
    </Modal>
  </el-card>
</template>

<script>
import {
  getMaintenanceSupplierOrderList,
  getTakingOrderInfo,
  takeOrder,
  completeOrder,
  getCompletedOrderImages,
  updateCompletedOrderImages
} from '@/api'

/* components
---------------------------------------------------------------- */
import { Query } from '@/mixins'
import ConfirmOrderForm from './components/ConfirmOrderForm'
import OrderImagesForm from './components/OrderImagesForm'

/* model
---------------------------------------------------------------- */
import { exportURL } from './model'
import { orderMStatusEnum, commonLogicalEnum } from '@/core/enum'
import { downloadBase64UseLoading } from '@/utils/http-download'

export default {
  mixins: [Query('query')],

  data () {
    return {
      showTip: false,

      total: 0,
      dataSource: [],
      loading: false,
      columns: [
        { prop: 'orderNumber', label: '订单编号' },
        { prop: 'orderDescribe', label: '订单备注' },
        { prop: 'orderCommunityName', label: '社区名称' },
        { prop: 'orderGoodsName', label: '商品名称' },
        { prop: 'orderAddress', label: '订单地址' },
        { prop: 'orderAmount', label: '订单金额' },
        { prop: 'orderStateValue', label: '订单状态' },
        { prop: 'orderGroupLeaderName', label: '所属团长' },
        {
          prop: 'orderReceivingOrders',
          label: '是否接单',
          formatter: (row) => {
            const canTakeOrder =
              row['orderReceivingOrders'] === false &&
              row['orderState'] === orderMStatusEnum.waitingService
            return (
              <el-link
                type={canTakeOrder ? 'primary' : 'default'}
                disabled={!canTakeOrder}
                onClick={() => {
                  if (canTakeOrder) {
                    this.onClickTakeOrder(row['orderId'])
                  }
                }}
              >
                接单
              </el-link>
            )
          }
        },
        {
          prop: 'orderTime',
          label: '创建时间',
          width: this.$V.cellSize.date,
          formatter: (row) => this.$formatTime(row['orderTime'])
        },
        {
          label: '操作',
          minWidth: this.$V.cellSize.action,

          formatter: this.getActionDecorator([
            {
              icon: null,
              action: this.onClickComplete,
              type: 'primary',
              label: '完成',
              style: (row) =>
                row['orderState'] !== orderMStatusEnum.waitingService
                  ? { color: '#c0c4cc' }
                  : {},
              disabled: (row) =>
                row['orderState'] !== orderMStatusEnum.waitingService
            },
            {
              icon: null,
              action: this.onClickImage,
              type: 'primary',
              label: '编辑维修图片',
              style: (row) =>
                row['orderState'] === orderMStatusEnum.waitingService
                  ? { color: '#c0c4cc' }
                  : {},
              disabled: (row) =>
                row['orderState'] === orderMStatusEnum.waitingService
            }
          ])
        }
      ],
      query: {
        communityName: '',
        goodsName: '',
        orderState: '',
        orderReceivingOrders: '',
        dateRange: [],
        startDate: '',
        endDate: ''
      },
      record: {},
      imageRecord: {},

      // -------- Modal ----------
      visible: false,
      modalLoading: false,

      imageActionType: 'create',
      imageModalLoading: false,
      imageModalVisible: false

      // -------- !Modal ----------
    }
  },
  methods: {
    getRealQueryParams (params) {
      let { dateRange, ...rest } = params
      return rest
    },
    // Requests
    // ------------------------------------------
    getMaintenanceSupplierOrderList (fn) {
      const { dateRange, ...rest } = this.query

      return this.Catch(getMaintenanceSupplierOrderList, {
        onOk (res) {
          this.dataSource = res.data.data
          this.total = res.data.total
        }
      })('loading', (fn || this.$noop)(rest))
    },

    takeOrder (id, time) {
      return this.Catch(takeOrder, {
        onOk () {
          this.$message.success('接单成功')
          this.getMaintenanceSupplierOrderList()
          this.visible = false
        },
        onError (err) {
          console.log(err)
        }
      })('modalLoading', id, time)
    },

    completeOrder (id, data) {
      return this.Catch(completeOrder, {
        onOk: () => {
          this.$message.success('操作成功')
          this.getMaintenanceSupplierOrderList()
          this.imageModalVisible = false
        }
      })(null, id, data)
    },

    getTakingOrderInfo (id, { onOk, onError }) {
      return this.Catch(getTakingOrderInfo, {
        onOk,
        onError
      })('loading', id)
    },

    getCompletedOrderImages (id, { onOk, onError }) {
      return this.Catch(getCompletedOrderImages, {
        onOk,
        onError
      })('loading', id)
    },

    updateCompletedOrderImages (id, data) {
      return this.Catch(updateCompletedOrderImages, {
        onOk: () => {
          this.$message.success(this.$t('updateOk'))
          this.getMaintenanceSupplierOrderList()
          this.imageModalVisible = false
        }
      })('imageModalLoading', id, data)
    },

    // Form
    // ------------------------------------------

    beforeReset () {
      this.query['startDate'] = ''
      this.query['endDate'] = ''
    },

    // Table
    // ------------------------------------------

    onClickTakeOrder (orderId) {
      this.getTakingOrderInfo(orderId, {
        onOk ({ data }) {
          this.record = {
            ...data,
            orderId
          }
          this.visible = true
        }
      })
    },

    onClickComplete ({ orderId }) {
      this.imageRecord = {
        orderId,
        completePicture: ''
      }
      this.imageModalVisible = true
    },

    onClickImage ({ orderId }) {
      this.getCompletedOrderImages(orderId, {
        onOk ({ data }) {
          this.imageRecord = {
            orderId,
            completePicture: data
          }
          // 修改维修图片操作
          this.imageActionType = 'update'
          this.imageModalVisible = true
        }
      })
    },

    // Modal
    // ------------------------------------------
    // 接单
    handleSubmit () {
      this.$refs.orderForm.submit((valid, values) => {
        if (valid) {
          const { orderId, appointmentTime } = values
          this.takeOrder(orderId, appointmentTime)
        }
      })
    },

    // 关闭modal清理数据
    handleClose () {
      this.visible = false
    },

    // 完成订单或修改维修图片
    handleComplete () {
      this.$refs.imageForm.submit((valid, values) => {
        if (valid) {
          const { orderId, completePicture } = values

          // eslint-disable-next-line standard/computed-property-even-spacing
          this[
            this.imageActionType === 'create'
              ? 'completeOrder'
              : 'updateCompletedOrderImages'
          ](orderId, {
            completePicture
          })
        }
      })
    },
    // --------------------------------------------- 导出 开始 ---------------------------------------------

    processExportParams () {
      const { pageSize, pageNum, dateRange, ...rest } = this.query
      return {
        ...rest
      }
    },
    async onClickBatchExport () {
      try {
        await downloadBase64UseLoading.bind(this)('loading')(
          exportURL,
          this.processExportParams()
        )
      } catch (err) {
        this.$message.warning(err.message)
      }
    }
    // --------------------------------------------- 导出 结束 ---------------------------------------------
  },
  computed: {
    orderStatus () {
      return this.$mapEnumToSelect(orderMStatusEnum)
    },

    commonLogical () {
      return this.$mapEnumToSelect(commonLogicalEnum, {
        valueTransfer: null,
        keyFilter: null
      })
    }
  },
  components: { ConfirmOrderForm, OrderImagesForm },

  created () {
    this.getMaintenanceSupplierOrderList()
    this.inject(this.getMaintenanceSupplierOrderList)

    this.$watch('query.dateRange', (val) => {
      try {
        this.query['startDate'] = val[0] || ''
        this.query['endDate'] = val[1] || ''
      } catch (e) {}
    })
    this.$nextTick(() => (this.showTip = true))
  }
}
</script>
